//
//  Area.m
//  CarTown
//
//  Created by xionghao on 15/9/9.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "Area.h"
#import <MJExtension.h>
#import "AppDelegate.h"

@implementation Area

@dynamic name;
@dynamic time;
+(void)addArea:(NSArray *)data{
    AppDelegate *delegate=[[UIApplication sharedApplication]delegate];
    NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@"Area"];
    NSArray *sets= [delegate.managedObjectContext executeFetchRequest:request error:nil];
    if (sets.count>0) {
        Area *area= sets[0];
        NSTimeInterval secondsInterval= [area.time timeIntervalSinceDate:[NSDate date]];
        if ([area.time isYesterday]||secondsInterval>24*60*60) {
            for (Area *a in sets) {
                [delegate.managedObjectContext deleteObject:a];
            }
            
            for (NSDictionary *dict in data) {
                Area *area=[NSEntityDescription insertNewObjectForEntityForName:@"Area" inManagedObjectContext:delegate.managedObjectContext];
                [area setValue:dict[@"name"] forKey:@"name"];
                [area setValue:[NSDate date] forKey:@"time"];
                [delegate saveContext];
            }
            
        }
        
    }else{
        for (NSDictionary *dict in data) {
            Area *a=[NSEntityDescription insertNewObjectForEntityForName:@"Area" inManagedObjectContext:delegate.managedObjectContext];
            [a setValue:dict[@"name"] forKey:@"name"];
            [a setValue:[NSDate date] forKey:@"time"];
            [delegate saveContext];
        }
        
    }

}
+(NSArray *)getArea{
    AppDelegate *delegate=[[UIApplication sharedApplication]delegate];
    NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@"Area"];
    NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
    request.sortDescriptors=@[sort];
    NSArray *sets= [delegate.managedObjectContext executeFetchRequest:request error:nil];
    return sets;

}
@end
